import tornado.ioloop
import tornado.web
from tortoise import Tortoise
import signal
import importlib.metadata
import tortoise.backends.mysql
import os
from core.utils import get_executable_path
from schedule_task import ScheduleTaskController
from dotenv import load_dotenv
import pytesseract

load_dotenv(dotenv_path=os.path.join(get_executable_path(), ".env"))

pytesseract.pytesseract.tesseract_cmd = os.getenv("PYTESSERACT_DIR")


frp_process = None

# # 强制加载包元数据
metadata = importlib.metadata.metadata('tortoise-orm')
# print(metadata)
# nuitka --standalone --mingw64 --onefile --windows-console-mode=disable --windows-icon-from-ico=logo.ico --output-filename=fast_vpn.exe app.py
# nuitka --standalone --mingw64 --onefile --windows-icon-from-ico=logo.ico --output-filename=fast_vpn83.exe app.py
# nuitka --standalone --mingw64 --windows-console-mode=disable --windows-icon-from-ico=logo.ico --output-filename=fast_vpn78.exe app.py

# pyinstaller --onefile --noconsole your_script.py
# pyinstaller --noconsole app.py
# pyinstaller --onefile --noconsole --version-file=file_version_info.txt --icon=icon.ico --name=DragonTrailDatabase app.py
# pyi-grab_version C:\Program Files\WonewMusic\WonewMusic.exe fsccc.txt

from app_handler.app_websocket_handler import AppWebSocketHandler
from app_handler.api_log_handler import ApiLogHandler
from app_handler.api_role_handler import ApiRoleHandler
from app_handler.api_schedule_handler import ApiScheduleHandler
from app_handler.api_craft_handler import ApiCraftHandler
from app_handler.api_screenshot_handler import ApiScreenshotHandler

def make_app():
  template_dir = os.path.join(get_executable_path(), "templates")
  application = tornado.web.Application([
    (r"/static/(.*)", tornado.web.StaticFileHandler, {"path": "static"}),
    (r"/screenshot/(.*)", tornado.web.StaticFileHandler, {"path": os.getenv("SCREENSHOT_DIR")}),
    (r"/api/log/(.*)", ApiLogHandler),
    (r"/api/screenshot/(.*)", ApiScreenshotHandler),
    (r"/api/role/(.*)", ApiRoleHandler),
    (r"/api/schedule/(.*)", ApiScheduleHandler),
    (r"/api/craft/(.*)", ApiCraftHandler),
    (r"/websocket", AppWebSocketHandler),
  ], template_path=template_dir, global_temp_vars={"data": 2})
  return application

async def init_db():
  # set password for 用户名@localhost = password('新密码');
  db_url = f'mysql://{os.getenv("MYSQL_USER")}:{os.getenv("MYSQL_PASSWORD")}@{os.getenv("MYSQL_HOST")}:{os.getenv("MYSQL_PORT")}/{os.getenv("MYSQL_DBNAME")}'

  await Tortoise.init(
      db_url=db_url,
      modules={'models': ['db']},
      timezone='Asia/Shanghai'  # 设置数据库的时区
  )
  # Generate the schema
  await Tortoise.generate_schemas(safe=True)
  
# 优雅地关闭 Tornado 应用
def shutdown_signal_handler(sig, frame):
  print("Received shutdown signal, shutting down Tornado...")
  tornado.ioloop.IOLoop.current().add_callback(shutdown)
  
async def shutdown():
  # 清理 WebSocket 连接、数据库连接等资源
  print("Shutting down the server...")
  await Tortoise.close_connections()  # 关闭数据库连接
  tornado.ioloop.IOLoop.current().stop()

# 设置信号处理
signal.signal(signal.SIGINT, shutdown_signal_handler)  # 捕获 Ctrl+C 信号
signal.signal(signal.SIGTERM, shutdown_signal_handler)  # 捕获终止信号


if __name__ == "__main__":
  tornado.ioloop.IOLoop.current().run_sync(init_db)
  app = make_app()
  app.listen(int(os.getenv("PORT", "8888")))
  print(f"Server started on http://localhost:{os.getenv('PORT', '8888')}")
  
  # 创建定时任务，每隔5秒执行一次
  pc = tornado.ioloop.PeriodicCallback(ScheduleTaskController().loop_task, 10000)  # 5000毫秒=5秒
  pc.start()
  
  tornado.ioloop.IOLoop.instance().start()
  